@RequestParam与@NotBlank、@NotNull验证注解 |
您所在的位置:网站首页 › 自定义注解 notnull › @RequestParam与@NotBlank、@NotNull验证注解 |
@RequestParam与@NotBlank、@NotNull验证注解,需不需要同时使用? 文章目录前言 一、使用步骤 1.@RequestParam和验证注解同时使用 2.@RequestParam和验证注解单独使用 总结 前言在Controller中可能会同时出现@RequestParam和验证注解(@NotBlank、@NotNull等),那么同时使用以哪种验证为准呢? 一、使用步骤 1.@RequestParam和验证注解同时使用代码如下: @RequestMapping("/test") public String test( @RequestParam(required = false, defaultValue = "") @NotBlank(message = "用户名不能为空") String name) return "success"; }说明: (1)如果url请求中有传参数,只需要验证@NotBlank; (2)如果url请求中没有传参数,@RequestParam中只要有defaultValue,不管required是true还是false,参数的值都赋为defaultValue的值,再验证@NotBlank; 例:@ReuqstParam(required=true, defaulfValue="张三") @NotBlank(message="用户名不能为空") String name此时没有传参,name为张三,虽然required值为true,但是不会报错。 (3)如果@RequestParam中required属性为true,没有defaultValue且url请求中没有传参,那么会返回@RequestParam的错误信息,不会返回@NotBlank的错误信息。 例:@RequestParam(required=true) @NotBlank(message = "用户名不能为空") String name此时没有传参,只会返回@RequestParam没有参数的错误。 注意:没有传参与没有参数值是有区别的,required限制的是url中有这个参数,参数的值是多少并不关心,如果没有值,会被赋值为null;@NotBlank限制的是参数的值不能为空(null或去除空白符长度为0)。没有传参,required=true时会报错,没有参数值,@NotBlank会报错。 2.@RequestParam和验证注解单独使用@RequestParam: @RequestMapping("/test") public String test( @RequestParam String name) return "success"; }说明:@RequestParam默认为true必填,这时候如果不传就会报错 Required String parameter 'name' is not present这时候的错误提示是英文的,不是很友好。 @NotBlank: @RequestMapping("/test") public String test( @NotBlank(message = "用户名不能为空") String name) return "success"; }说明:这时候报错信息就是message定义的错误 test.name: 用户名不能为空这时候的提示信息就比较友好,可以全局异常捕捉,封装后返回提示信息给前端: SpringBoot注解校验validation自定义异常返回错误消息给前端_涛哥是个大帅比的博客-CSDN博客 总结如果参数不需要默认值,使用@NotBlank、@NotNull验证注解比较友好。 @NotBlank注解String字段会报错_涛哥是个大帅比的博客-CSDN博客 |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |